<?php
class Forum_Db_Table
{
    protected $_name = '';
    
    /**
     * Retrieve Forum_Db object from registry
     * 
     * @return Forum_Db
     */
    public function getAdapter()
    {
        return Forum::registry('db');
    }
    
    /**
     * Fetches rows by primary key
     * 
     * @return array
     * @throws Exception
     */
    public function find()
    {
        $args = func_get_args();
        $keyNames = array_values((array) $this->_primary);
        
        if (count($args) < count($keyNames)) {
            throw new Exception("Too few columns for the primary key");
        }

        if (count($args) > count($keyNames)) {
            throw new Exception("Too many columns for the primary key");
        }
        
        $query = "SELECT * FROM {$this->_name} WHERE ";
        
        $where = array();
        foreach ($keyNames as $index => $name) {
            $where[] = "{$name} = {$args[$index]}";
        }
        
        $query .= implode(' AND ', $where);
        
        return $this->getAdapter()->fetchAssoc($query);
    }
    
    /**
     * 
     * @param string $method
     * @param mixed $args
     */
    public function __call($method, $args)
    {
        $fields = explode('By', substr($method, 3));
        
        $returnField = strtolower($fields[0]);
        
        $conditionField = strtolower($fields[1]);
        
        $conditionValue = current($args);
        
        return $this->getAdapter()->fetchOne(
           "SELECT {$returnField} FROM " . $this->_name . " WHERE {$conditionField} = '{$conditionValue}'" 
        );
    }
}